from django.shortcuts import render, redirect
from django.http import HttpResponse, JsonResponse
from ..models import Department, UserInfo, PrettyNum, Task, Order, Boss, City
from django import forms
from django.forms import Form, ModelForm
from django.utils.safestring import mark_safe
from ..utils.pagination import Pagination
from ..utils.bootstrap import BootStrapModelForm, BootStrap
from ..utils.form import UserModelForm, PrettynumModelForm, PrettynumEditModelForm
from django.core.validators import RegexValidator
from django.core.exceptions import ValidationError
from django.views.decorators.csrf import csrf_exempt
import json
from datetime import datetime
from django.views.decorators.csrf import csrf_exempt
import random
import os
from django.conf import settings

@csrf_exempt
def upload_list(request):
    if request.method == 'GET':
        return  render(request, 'upload_list.html')
    file_object = request.FILES.get('avatar')
    f = open(file_object.name, mode='wb')
    for chunk in file_object.chunks():
        f.write(chunk)
    f.close()
    return HttpResponse('上传成功')

class UpForm(BootStrap):
    bootstrap_exclude_fields = ['img']
    name = forms.CharField(label="姓名")
    age = forms.IntegerField(label='年龄')
    img = forms.FileField(label='头像')

def upload_form(request):
    if request.method == 'GET':
        title = 'Form上传'
        form = UpForm()
        return render(request, 'upload_form.html', {'form': form})
    form = UpForm(data=request.POST, files=request.FILES)
    if form.is_valid():
        image_object = form.cleaned_data.get('img')
        media_path = os.path.join(settings.MEDIA_ROOT, image_object.name)
        f = open(media_path, 'wb')
        for chunk in image_object.chunks():
            f.write(chunk)
        f.close()
        Boss.objects.create(
            name=form.cleaned_data['name'],
            age=form.cleaned_data['age'],
            img=media_path
        )
        return HttpResponse('新建成功')
    return render(request, 'upload_form.html', {'form': form})

class UpModelForm(BootStrapModelForm):
    bootstrap_exclude_fields = ['img']
    class Meta:
        model = City
        fields = '__all__'

def upload_modelform(request):
    if request.method == 'GET':
        form = UpModelForm()
        return render(request, 'upload_form.html', {'form': form, 'title': 'ModelForm上传'})

    form = UpModelForm(data=request.POST, files=request.FILES)
    if form.is_valid():
        form.save()
        return HttpResponse('上传成功')
    return render(request, 'upload_form.html', {'form': form, 'title': 'ModelForm上传'})